package com.hui.platform.falseworkapi.common.security.jwt;

import com.alibaba.fastjson.JSON;
import com.hui.platform.falseworkapi.common.core.constant.ResultCodeEnum;
import com.hui.platform.falseworkapi.common.core.vo.CommonResult;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  拒绝访问处理器 （403--4003）
 *  认证失败，当访问接口没有权限时，自定义的返回结果
 *
 * @author Peng
 * @date 2019/12/5
 */
public class JsonAccessDeniedHandler implements AccessDeniedHandler {

    private final MessageSource messageSource;

    public JsonAccessDeniedHandler(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
    	//响应请求
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //设置跨域
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Origin","*");
        //设置响应码403
        response.setStatus(HttpStatus.FORBIDDEN.value());
        //包装数据
        CommonResult<String> forbidden = CommonResult.build(ResultCodeEnum.FORBIDDEN, messageSource, null, e.getMessage());
        response.getWriter().println(JSON.toJSONString(forbidden));
        response.getWriter().flush();
    }
}
